import openpyxl
from openpyxl.styles import Alignment
from django.http import HttpResponse
from io import BytesIO
from django.db.models.fields.files import ImageFieldFile


class ExcelHandler:
    @staticmethod
    def export_data(queryset, model_class, filename):
        wb = openpyxl.Workbook()
        ws = wb.active
        
        # 获取模型字段（排除自动生成的ID）
        fields = [field for field in model_class._meta.fields if not field.auto_created]
        
        # 写入表头
        for col, field in enumerate(fields, 1):
            ws.cell(row=1, column=col, value=field.verbose_name)
            # 设置表头样式
            ws.cell(row=1, column=col).alignment = Alignment(horizontal='center', vertical='center')
        
        # 写入数据行
        for row, obj in enumerate(queryset, 2):
            for col, field in enumerate(fields, 1):
                field_name = field.name
                value = getattr(obj, field_name)
                
                # 专门处理ImageFieldFile类型（包括None值）
                if isinstance(value, ImageFieldFile):
                    if value and value.name:  # 检查是否有实际图片
                        # 可以选择存储图片路径或URL
                        cell_value = value.name  # 存储相对路径，如"house/covers/img1.jpg"
                        # 或使用 cell_value = value.url 存储完整URL
                    else:
                        cell_value = "无图片"  # 空图片字段的占位文本
                    
                    ws.cell(row=row, column=col, value=cell_value)
                
                # 处理其他可能的特殊类型
                elif value is None:
                    ws.cell(row=row, column=col, value="")  # 空值处理
                
                # 普通字段直接写入
                else:
                    try:
                        # 尝试直接写入值
                        ws.cell(row=row, column=col, value=str(value))
                    except Exception as e:
                        # 捕获其他可能的转换错误
                        ws.cell(row=row, column=col, value=f"转换错误: {str(e)[:20]}")
        
        # 调整列宽
        for col in range(1, len(fields) + 1):
            ws.column_dimensions[openpyxl.utils.get_column_letter(col)].width = 20
        
        # 保存到内存
        buffer = BytesIO()
        wb.save(buffer)
        buffer.seek(0)
        
        # 构建响应
        response = HttpResponse(
            buffer.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response
